package com.yanqu.road.server.cmd.activity.union;

import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.ChannelTonBingProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.connect.CrossAgentLinkedControl;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.*;

@Cmd(code = CrossProtocol.C3_CHANNEL_ACTIVITY_GET_UNION_INFO, desc = "")
public class Cross3GetUnionReqCmd extends CrossCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        ChannelTonBingProto.ChannelGetUnionReqMsg reqMsg = ChannelTonBingProto.ChannelGetUnionReqMsg.parseFrom(packet.getBytes());
        int activityId = reqMsg.getActivityId();
        int channelId = reqMsg.getChannelId();
        List<Long> serverIds = reqMsg.getServerIdList();
        int topCount = reqMsg.getTopCount();
        CrossUnionProto.ChannelGetUnionMaxAbilityRankListResp.Builder builder = CrossUnionMgr.getCTopMaxAbilityUnionListMsg(activityId,channelId,serverIds,topCount);
        RandomHelper randomHelper = new RandomHelper();
        List<Long> serverIdList = new ArrayList<>(reqMsg.getServerIdList());
        while (serverIdList.size() > 0){
            int index = randomHelper.next(0,serverIdList.size());
            long serverId = serverIdList.get(index);
            int serverChannelId = ServerListMgr.getChannelId(serverId);
//            if(CrossAgentLinkedControl.isSeverIdConnection(serverId)){
            if(serverChannelId == channelId){
                MessageHelper.sendPacket(serverId,0,YanQuMessageUtils.buildMessage(CrossProtocol.C2_CHANNEL_ACTIVITY_GET_UNION_INFO_BACK, builder));
                return;
            }else{
                serverIdList.remove(serverId);
            }
        }
    }

    @Override
    public void sendData() {

    }

}
